package cn.ruituo.util;

import java.io.IOException;
import java.sql.*;
import java.util.Base64;
import java.util.Properties;

/**
 * @author oldliu
 * @since 1.0
 */
public class DBUtil {
    private static String url = "jdbc:mysql://localhost:3306/java72db?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2b8&rewriteBatchedStatements=true";
    private static String driver = "com.mysql.jdbc.Driver";
    private static String user = "root";
    private static String pass = "root1234";

    //private static ResultSet rs;

    private DBUtil() {
    }

    //静态代码块，第一次加载的时候才执行
    static {
        //读取jdbc.properties
        Properties p = new Properties();
        try {
            p.load(DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            url = p.getProperty("url");
            driver = p.getProperty("driver");
            user = p.getProperty("user");
            pass = p.getProperty("pass");
            byte[] decoded = Base64.getDecoder().decode(pass);
            pass = new String(decoded);
            //?>>>
            decoded = Base64.getDecoder().decode(pass);
            pass = new String(decoded);

        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            Class.forName(driver);//Class
        } catch (ClassNotFoundException e) {
            System.out.println("没有找到驱动");
            e.printStackTrace();
            //System.exit(0);

        }
    }

    public static Connection getConnection() {

        try {
            return DriverManager.getConnection(url, user, pass);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //all
    public static void close(ResultSet rs, Statement st, Connection con) {
        close(rs);
        close(st);
        close(con);
    }

    public static void close(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Statement rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void handleException(Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}
